package util;

import java.io.FileOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

import certificate.X509CertificateHandler;

public abstract class KeyStoreHandler {

	/**
	 * 
	 * @param DNName dnString which you pass to the certificate
	 * @param fileName where to store the KeyStore
	 * @param alias under what alias to store new keys
	 * @return boolean fail or not
	 */
	public boolean createAndStoreNewPrivateAndPublicKey(String DNName, String alias, String fileName){
    	KeyPairGenerator keyGen;
		try {
			keyGen = KeyPairGenerator.getInstance("RSA");
	    	SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
	        keyGen.initialize(2048, random);
	        KeyPair pair = keyGen.generateKeyPair();
	        X509Certificate cert = X509CertificateHandler.generate(DNName, pair, "SHA1withRSA", 30);
	        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        	ks.load(null, "".toCharArray());
        	Certificate[] certChain = {cert};
        	// we save a keystore object with a pesel as an identifier string and
        	// secret code as a password
    		ks.setKeyEntry(alias,pair.getPrivate(),"".toCharArray(),certChain);
    		FileOutputStream foStream = new FileOutputStream(fileName);
    		ks.store(foStream,"".toCharArray());
    		return true;
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e1);
		}
	}
}
